﻿using MediatR;
using W.Purchase.Domain.PageDTO;
using W.Purchase.Domain;
using W.Purchase.Read.API.AppLication.Command.FinanceTotalCommand;
using W.Purchase.Repository.Interface;

namespace W.Purchase.Read.API.AppLication.CommandHandler.FinanceTotalCommandHandler
{
    public class FinanceTotalShowCommandHandler : IRequestHandler<FinanceTotalShowCommand, Pages<FinanceTotalDTO>>
    {
        private readonly IReceivableRepository _ireceivableRepository;
        private readonly IPayableRepository _ayableRepository;
        public FinanceTotalShowCommandHandler(IReceivableRepository ireceivableRepository, IPayableRepository ayableRepository)
        {
            _ireceivableRepository = ireceivableRepository;
            _ayableRepository = ayableRepository;
        }

        public async Task<Pages<FinanceTotalDTO>> Handle(FinanceTotalShowCommand request, CancellationToken cancellationToken)
        {
            Pages<FinanceTotalDTO> page = new Pages<FinanceTotalDTO>();
            var rlist = await _ireceivableRepository.GetAllAsaync();
            var plist = await _ayableRepository.GetAllAsaync();
            var list = rlist.Select(x => new 
            {
                x.ReceivableId,
                x.ReceivableSerialNumber,
                x.ReceivableName,
                x.FinanceTypeName,
                x.Payer,
                x.Payee,
                x.PracticalMoey,
                x.StyleStatus,
                x.CreateTime
            })
            .Concat(plist.Select(y => new 
            {
                ReceivableId=y.PayableId,
                ReceivableSerialNumber=y.PayableSerialNumber,
                ReceivableName=y.PayableName,
                FinanceTypeName = y.FinanceTypeName,
                Payer = y.Payer,
                Payee = y.Payee,
                PracticalMoey = y.ActuallyPaidMoney,
                StyleStatus = y.StyleStatus,
                CreateTime = y.CreateTime

            }))
            .ToList();
            page.TotalPage = list.Count();
            page.TotalCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.PageSize);
            //page.List=list.OrderByDescending(c=>c.ReceivableId).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
            return page;
        }
    }
}
